package renguanyu.app.auth4fx.controller.role;

import javafx.concurrent.Task;
import renguanyu.app.auth4fx.App;
import renguanyu.app.auth4fx.model.role.RoleDto;
import renguanyu.app.auth4fx.service.role.RoleService;
import renguanyu.app.auth4fx.view.role.RoleInfoUpdateView;
import renguanyu.app.auth4fx.view.role.RoleListView;

public class RoleInfoUpdateController extends Task<Void> {

    RoleInfoUpdateView roleInfoUpdateView;
    public RoleInfoUpdateController(RoleInfoUpdateView roleInfoUpdateView) {
        this.roleInfoUpdateView = roleInfoUpdateView;
    }

    public void execute() {
        System.out.println("RoleInfoUpdate.execute");
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.start();
    }

    private Integer affectedRows = 0;
    @Override
    protected Void call() {
        System.out.println("RoleInfoUpdate.call");
        RoleDto roleDto = buildRoleDto();
        affectedRows = RoleService.updateRole(roleDto);
        return null;
    }

    private RoleDto buildRoleDto() {
        String id = roleInfoUpdateView.selectedRole.getId();
        String name = roleInfoUpdateView.nameProperty.get();
        RoleDto roleDto = new RoleDto();
        roleDto.setId(id);
        roleDto.setName(name);
        return roleDto;
    }

    @Override
    protected void running() {
        System.out.println("RoleInfoUpdate.running");
    }

    @Override
    protected void succeeded() {
        System.out.println("RoleInfoUpdate.succeeded");
        if(affectedRows == 1){
            App.mainView.setCenter(new RoleListView());
        }
    }

    @Override
    protected void failed() {
        System.out.println("RoleInfoUpdate.failed");
    }
}
